package com.cnhis.cloudhealth.clinical.clidoctor.basicinformationquery.bo;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cnhis.cloudhealth.clinical.clidoctor.basicinformationquery.dao.BasicInformationQueryDao;
import com.cnhis.cloudhealth.commons.Mappers.ModelVo;
import com.cnhis.cloudhealth.commons.utils.DateUtils;
import com.cnhis.cloudhealth.commons.utils.GlobalVariable;
import com.cnhis.cloudhealth.commons.utils.Page;
import com.cnhis.cloudhealth.commons.utils.StaticKeys;
import com.cnhis.cloudhealth.commons.utils.jpinyin.CnToWB;
import com.cnhis.cloudhealth.commons.utils.jpinyin.PinyinHelper;

@Service
public class BasicInformationQueryBo {
	@Resource
	private BasicInformationQueryDao basicInformationQueryDao;
	Logger log = Logger.getLogger(BasicInformationQueryBo.class);
	public ModelVo treatmentItemQuery(Map map)throws Exception{
		ModelVo mo = new ModelVo();
		List list =null;
		try {
			list=basicInformationQueryDao.treatmentItemQuery(map);
			
		} catch (Exception e) {
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		mo.setList(list);
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setRows(list);
		return mo;
	}
	public ModelVo queryPrescriptionType(int currPage,int pageSize)throws Exception{
		ModelVo mo = new ModelVo();
		Page pg = null;
		try {
			pg =basicInformationQueryDao.queryPrescriptionType(currPage, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		
		mo.setList(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		mo.setRows(pg.getList());
		return mo;
	}
	public ModelVo illnessDirectory(Map map,int currPage,int pageSize)throws Exception{
		ModelVo mo = new ModelVo();
		Page pg = null;
		try {
			pg =basicInformationQueryDao.illnessDirectory(map, currPage, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		
		mo.setList(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		mo.setRows(pg.getList());
		return mo;
	}
	public ModelVo chineseMedicineTreatment(int currPage,int pageSize)throws Exception{
		ModelVo mo = new ModelVo();
		Page pg = null;
		try {
			pg =basicInformationQueryDao.chineseMedicineTreatment(currPage, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		
		mo.setList(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		mo.setRows(pg.getList());
		return mo;
	}
	public ModelVo feeItem(Map map,int currPage,int pageSize)throws Exception{
		ModelVo mo = new ModelVo();
		Page pg = null;
		try {
			pg =basicInformationQueryDao.feeItem(map, currPage, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		
		mo.setList(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		mo.setRows(pg.getList());
		return mo;
	}
	public ModelVo defaultPharmacy(Map map,int currPage,int pageSize)throws Exception{
		ModelVo mo = new ModelVo();
		Page pg = null;
		try {
			pg =basicInformationQueryDao.defaultPharmacy(map, currPage, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
			mo.setResult(StaticKeys.OH_FALSE);
			return mo;
		}
		
		mo.setList(pg.getList());
		mo.setResult(StaticKeys.OH_SUCCESS);
		mo.setTotal(pg.getTotalNumber());
		mo.setRows(pg.getList());
		return mo;
	}
    public ModelVo zhixingkeshi1(HashMap map)
    {
        ModelVo mo = new ModelVo();
        List list = new ArrayList<>();
        try {
            list =basicInformationQueryDao.zhixingkeshi1(map);
            mo.setList(list);
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        } catch (Exception e) {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
        
       
    }
    @SuppressWarnings({"unchecked", "rawtypes"})
    public ModelVo updateVaaVacVcj(Long vAC01, Map map)
    {
        ModelVo mo = new ModelVo();
        try {
//            map.put("vac01", vAC01);
            List iar1List = basicInformationQueryDao.queryForList("BasicInformationQuery.hasIar1",map);
            if(iar1List !=null && iar1List.size()>0)
            {
                mo.setResult(StaticKeys.OH_FALSE);
                mo.setResultMsg("此病人本次就诊已存在医保结账记录，不允许修改保险号和险种名称！");
                return mo;
            }
            for(String temp : (Set<String>)map.keySet())
            {
                if("".equals(map.get(temp)))
                {
                    map.put(temp, null);
                }
            }
            String vaa05 = map.get("vaa05").toString();
            map.put("abbrp", PinyinHelper.getShortPinyin(vaa05));
            map.put("abbrw", CnToWB.getWBCode(vaa05));
            String vac68 = GetAgeDetailFromAge(0, "Y", DateUtils.String2Date(GlobalVariable.StringIsNull(map.get("vaa12"))));
            map.put("vac68", vac68);
            basicInformationQueryDao.update("BasicInformationQuery.updateVaaVacVcj", map);
            mo.setResult(StaticKeys.OH_SUCCESS);
            return mo;
        } catch (Exception e) {
            e.printStackTrace();
            mo.setResult(StaticKeys.OH_FALSE);
            return mo;
        }
    }
    
    /**
     *  计算明细年龄问题    小于14岁显示到月，小于1岁显示到天
     * @param VAA10
     * @param AAU01
     * @param VAA12
     * @return
     * @throws Exception
     */
    
    @SuppressWarnings({ "deprecation", "static-access" })
    public String GetAgeDetailFromAge(int VAA10, String AAU01, Date VAA12) throws Exception {
        String sAge = null;
        Date aDate = new Date();
        int amode = 0;
        int aYear = 0;
        int aMonth = 0;
        int aDay = 0;
        int bDay = 0;
        String rvalue = "";
        int ahour = 0;
        int amin = 0;
        Date t1 = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(t1);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        Date tempDate = cal.getTime();
        VAA12 = (Date) (VAA12 == null ? tempDate : VAA12);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 可以方便地修改日期格式
        if (VAA12.getTime() - dateFormat.parse("1912-01-01").getTime() < 0) {
            if (VAA10 <= 0) {
                rvalue = "";
            } else {
                sAge = VAA10 + "";
                rvalue = sAge + AAU01;
            }
        } else {
            if (amode == 0) {
                aDay = dateDiff(VAA12, aDate, "day").intValue();
                if (aDay > 0) {
                    Calendar calaDate = Calendar.getInstance();
                    aMonth = dateDiff(VAA12, aDate, "month").intValue();
                    calaDate.setTime(aDate);
                    Calendar calVaa12 = Calendar.getInstance();
                    calVaa12.setTime(VAA12);
                    aDay = calaDate.get(calaDate.DAY_OF_MONTH) - calVaa12.get(calVaa12.DAY_OF_MONTH);
                    aYear = aMonth / 12;
                    aMonth = aMonth % 12;
                    if (aDay < 0) {
                        aMonth = aMonth - 1;
                    }
                    if (aMonth < 0) {
                        aYear = aYear - 1;
                        aMonth = 12 + aMonth;
                    }
                    if (aDay < 0) {
                        cal.setTime(VAA12);
                        cal.add(Calendar.MONTH, aMonth);// 增加一個月
                        cal.add(Calendar.YEAR, aYear);// 增加一個月
                        VAA12 = cal.getTime();
                        aDay = dateDiff(VAA12, aDate, "day").intValue();
                    }
                    if (aYear > 0) {
                        rvalue = rvalue + aYear + "Y";
                    }
                    if (aMonth > 0 && aYear < 14) {
                        rvalue = rvalue + aMonth + "M";
                    }
                    if (aDay > 0 && aYear < 1) {
                        rvalue = rvalue + aDay + "D";
                    }
                } else if (aDay == 0) {
                    amin = dateDiff(VAA12, aDate, "min").intValue();
                    if (amin > 0) {
                        ahour = amin / 60;
                        if (ahour == 0) {
                            rvalue = amin + "N";
                        } else if (ahour > 0) {
                            rvalue = ahour + "H";
                        }
                    }
                }

            } else {
                aYear = dateDiff(VAA12, aDate, "year").intValue();
                if (VAA12.getMonth() > aDate.getMonth()
                        || VAA12.getMonth() == aDate.getMonth() && VAA12.getDay() > aDate.getDay()) {
                    aYear = aYear - 1;
                    aMonth = dateDiff(VAA12, aDate, "month").intValue();
                }
                if (VAA12.getDay() > aDate.getDay()) {
                    aMonth = aMonth - 1;
                    aMonth = aMonth % 12;
                    cal.setTime(VAA12);
                    cal.add(Calendar.MONTH, 1);// 增加一個月
                    VAA12 = cal.getTime();
                    Calendar cal1 = Calendar.getInstance();
                    int day_of_month = cal1.get(Calendar.DAY_OF_MONTH);
                    cal1.add(Calendar.DATE, -day_of_month);
                    bDay = cal1.get(Calendar.DATE);
                    if (aYear > 0 || aMonth > 0 || (aYear <= 0 && aMonth <= 0) && VAA12.getDay() <= aDate.getDay()) {
                        aDay = Math.abs(aDate.getDay() - VAA12.getDay());
                    } else {
                        aDay = bDay - VAA12.getDay() + aDate.getDay();
                    }
                    if (aYear > 0) {
                        rvalue = rvalue + aYear + "Y";
                    }
                    if (aMonth > 0 && aYear < 14) {
                        rvalue = rvalue + aMonth + "M";
                    }
                    if (aDay > 0 && aYear < 1) {
                        rvalue = rvalue + aDay + "D";
                    }
                    if (dateDiff(VAA12, aDate, "day").intValue() < 0) {
                        rvalue = "";
                    }
                }

            }
        }
        return rvalue;
    }
    
    /**
     * 按指定日期单位计算两个日期间的间隔
     * 
     * @param timeInterval
     * @param date1
     * @param date2
     * @return
     */
    public static Long dateDiff(Date date2, Date date1, String timeInterval) {
        if (timeInterval.equals("year")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.YEAR));
        }

        if (timeInterval.equals("quarter")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 4;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 4;
            calendar.setTime(date1);
            time += calendar.get(Calendar.MONTH) / 4;
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.MONTH) / 4);
        }

        if (timeInterval.equals("month")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 12;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 12;
            calendar.setTime(date1);
            time += calendar.get(Calendar.MONTH);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.MONTH));
        }

        if (timeInterval.equals("week")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int time = calendar.get(Calendar.YEAR) * 52;
            calendar.setTime(date2);
            time -= calendar.get(Calendar.YEAR) * 52;
            calendar.setTime(date1);
            time += calendar.get(Calendar.WEEK_OF_YEAR);
            calendar.setTime(date2);
            return (long) (time - calendar.get(Calendar.WEEK_OF_YEAR));
        }

        if (timeInterval.equals("day")) {
            long time = Math.round(date1.getTime() / 1000 / 60 / 60 / 24);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00 / 60.00 / 24.00);
        }

        if (timeInterval.equals("hour")) {
            long time = Math.round(date1.getTime() / 1000 / 60 / 60);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00 / 60.00);
        }

        if (timeInterval.equals("minute")) {
            long time = Math.round(date1.getTime() / 1000 / 60);
            return time - Math.round(date2.getTime() / 1000.00 / 60.00);
        }

        if (timeInterval.equals("second")) {
            long time = Math.round(date1.getTime() / 1000);
            return time - Math.round(date2.getTime() / 1000.00);
        }

        return date1.getTime() - Math.round(date2.getTime());
    }
    public ModelVo getBciInfo(Map<String, Object> map)throws Exception
    {
        ModelVo mv = new ModelVo();
        mv.setList(basicInformationQueryDao.queryForList("BasicInformationQuery.getBciInfo", map));
        return mv;
    }


    public ModelVo queryBase(Map<String, Object> paramMap) throws Exception {
        ModelVo mv = new ModelVo();
        log.info("sqlId================="+paramMap.get("sqlId"));
        List sqlList = (List) basicInformationQueryDao.queryForList("BasicInformationQuery.querySqlDb",paramMap);
        String sqlDb = GlobalVariable.StringIsNull(((Map<String,Object>)sqlList.get(0)).get("xtext1"));
        Set<String> keySet = paramMap.keySet();
        for(String key : keySet)
        {
            sqlDb = sqlDb.replaceAll("@"+key,paramMap.get(key).toString());
        }
        Map<String,String> sqlMap = new HashMap<String,String>();
        sqlMap.put("sql",sqlDb);
        List<Map<String,Object>> list = basicInformationQueryDao.queryForList("BasicInformationQuery.baseQuery",sqlMap);
        mv.setResult(StaticKeys.OH_SUCCESS);
        mv.setUserdata(sqlDb.replaceAll("\t","").replaceAll("\n","").replaceAll("\r",""));
        mv.setList(list);
        return mv;
    }
    public ModelVo updateProc(Map<String, Object> map) throws Exception
    {
        ModelVo mv = new ModelVo();
        basicInformationQueryDao.updateProc(map);
        mv.setResult(StaticKeys.OH_SUCCESS);
        return mv;
    }
    public ModelVo updateProc1(Map<String, Object> map) throws Exception
    {
        ModelVo mv = new ModelVo();
        basicInformationQueryDao.updateProc1(map);
        String msg = GlobalVariable.StringIsNull(map.get("msg"));
        if(msg.isEmpty())
        {
            mv.setResult(StaticKeys.OH_SUCCESS);
        }
        else
        {
            mv.setResult(StaticKeys.OH_FALSE);
            mv.setResultMsg(msg);
        }
        return mv;
    }
    
    public ModelVo queryBasePage(Map<String, Object> paramMap) throws Exception
    {
        ModelVo mv = new ModelVo();
        int currPage = GlobalVariable.IntegerIsNull(paramMap.get("currPage"));
        int pageSize = GlobalVariable.IntegerIsNull(paramMap.get("pageSize"));
        
        //获取sql
        List sqlList = (List) basicInformationQueryDao.queryForList("BasicInformationQuery.querySqlDb",paramMap);
        String sqlDb = GlobalVariable.StringIsNull(((Map<String,Object>)sqlList.get(0)).get("xtext1"));
        Set<String> keySet = paramMap.keySet();
        for(String key : keySet)
        {
            sqlDb = sqlDb.replaceAll("@"+key,paramMap.get(key).toString());
        }
        
        //分页查询
        Map<String,String> sqlMap = new HashMap<String,String>();
        sqlMap.put("sql",sqlDb+" limit "+pageSize+" offset "+((currPage-1)*pageSize));
        List<Map<String,Object>> list = basicInformationQueryDao.queryForList("BasicInformationQuery.baseQuery",sqlMap);
        
        //查询总数
        Map<String,String> sqlMapCount = new HashMap<String,String>();
        sqlMapCount.put("sql","select count(1) count from ("+sqlDb+") t_c");
        List<Map<String,Object>> listCount = basicInformationQueryDao.queryForList("BasicInformationQuery.baseQuery",sqlMapCount);
        
        mv.setResult(StaticKeys.OH_SUCCESS);
        mv.setUserdata(sqlDb.replaceAll("\t","").replaceAll("\n","").replaceAll("\r",""));
        mv.setRows(list);
        mv.setRecords(GlobalVariable.IntegerIsNull(listCount.get(0).get("count")));
        return mv;
    }
}
